package com.example.warehouse.filter;

import com.example.warehouse.config.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@WebFilter(filterName = "jwtFilter", urlPatterns = "/*")
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");  // 获取请求头中的Token

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);  // 去掉"Bearer "前缀
            if (!JWTUtil.isTokenExpired(token)) {
                Claims claims = JWTUtil.parseToken(token);  // 解析Token
                String username = claims.getSubject();  // 获取用户名
                // 可以把用户名存入SecurityContext等，或者做其他验证
                request.setAttribute("username", username);  // 将用户名存入请求中，后续可以使用
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  // Token过期
                response.getWriter().write("Token已过期");
                return;
            }
        }

        filterChain.doFilter(request, response);  // 继续请求处理
        }
}